ok, i figured out how to build the linked list. but now my program freezes when i try to copy a string to string inside of the struct.
here is the latest code:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "template_wordstat.h"
entry * append() ;
int main(int argc, char* argv[])
{
FILE* fp;
char line[MAX_LINE];
int i = 0;
char *nextWord;
entry *start = NULL;
/* Checks for correct usage and handles arguments accordingly */
if (argc != 2) {
fprintf(stderr, "Error: wrong number of parameters.\n");
return -1;
}
if (strcmp(argv[1],"-h") == 0) {
printf("Usage: wordstat FILE_NAME\n");
return 0;
}
if ((fp=fopen(argv[1],"r")) == NULL) {
fprintf(stderr, "Error: cannot open file %s.\n", argv[1]);
return -2;
}
while (! feof(fp)) {
/* reads one line at a time */
if (fgets(line, MAX_LINE, fp) == NULL)
break;
if (line[0] == '\n') /* empty line */
continue;
/* extract words from the line and handle the words */
nextWord = strtok (line, TS);
/* if the first token is empty, then there are no words */
if(nextWord == NULL){
fprintf(stderr, "File contains no words.\n");
return -2;
}
/* go through each word and build linked list with entries*/
while(nextWord != NULL){
entry *marker;
entry *temp = append();
marker = start;
printf(nextWord); //this prints the word just fine
////////////////////////////// here is where the trouble starts
temp->word = malloc(sizeof(strlen(nextWord)+1));
strcpy(temp->word, nextWord);
////////////////////////////// if i remove the above 2 lines, my program runs and ends fine
temp->count = 0;
/* If the very first node is empty */
if (start == NULL) {
start = temp;
start -> next = NULL;
}
else {
while(marker -> next != NULL)
marker = marker -> next;
temp -> next = NULL;
marker -> next = temp;
}
nextWord = strtok (NULL, TS);
}
}
/* sorting and printing */
fclose(fp);
return 0;
}
entry *append() {
entry *temp = malloc(sizeof(entry));
return temp;
}
i'm so frustrated :[